package com.moter.demo01.juc.alllocks.reentrantlock;

import java.util.concurrent.TimeUnit;

/**
 * 可重入锁
 */
public class MyReentrantLock {
    private boolean isLocked = false;//锁是否被占有
    private int lockCount = 0;//重入的次数
    private Thread lockOwner = null;//当前锁的拥有者

    public synchronized void lock(){
        Thread thread=Thread.currentThread();
//        System.out.println(thread.getName());
        while(isLocked&&lockOwner!=thread){//如果当前锁被占有，且当前线程不是锁的拥有者，就阻塞
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(thread.getName());
        isLocked=true;
        lockCount++;
        lockOwner=thread;
    }
    public synchronized void unlock(){
        lockCount--;
        if(lockCount==0){
            lockOwner=null;
            isLocked=false;
            notify();
        }else if(lockCount<0){
            throw new IllegalMonitorStateException("解锁次数不能超过加锁次数");
        }
    }

    public static void main(String[] args) {
        MyReentrantLock lock = new MyReentrantLock();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                lock.lock();
                lock.lock();
                try {
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                    lock.unlock();
                }
            }).start();
        }
    }

}
